import { promises as nodeFileSys } from "fs";
import * as nodeFileSystem from "fs";
import * as nodePath from "path";
import {FileSystem} from "./FileSystem";
import {FilePath} from "./FilePath";
import {sysFolder} from "./SysFolder";

export namespace DynamicWallpaper {
    export interface CopyDirFileResultBase {
        file: string;
    }
    export interface CopyDirFileResultSuccess extends CopyDirFileResultBase {
        copied: true;
    }
    export interface CopyDirFileResultFail extends CopyDirFileResultBase {
        copied: false;
        reason: Error;
    }
    export type CopyDirFileResult = CopyDirFileResultFail | CopyDirFileResultSuccess;
}

export class DynamicWallpaper {
    public static readonly DIR_SAVE = FilePath.posixJoin(sysFolder.homeDir, "./Library/Containers/whbalzac.Dongtaizhuomian/Data/Documents/Videos");
    public static readonly DIR_SAVE_SCREEN_PROTECTED = FilePath.posixJoin(sysFolder.homeDir, "./Library/Containers/com.apple.ScreenSaver.Engine.legacyScreenSaver/Data/Documents");
    private static instance: DynamicWallpaper;

    private constructor() {
    }

    public static getInstance() {
        if (!this.instance) {
            this.instance = new DynamicWallpaper();
        }
        return this.instance;
    }

    public static addToScreenProtectedDir(filename: string, relPath?: string): Promise<DynamicWallpaper.CopyDirFileResult> {
        if (!relPath) {
            relPath = nodePath.basename(filename);
        }
        return nodeFileSys.copyFile(filename, nodePath.join(DynamicWallpaper.DIR_SAVE_SCREEN_PROTECTED, relPath)).then((): DynamicWallpaper.CopyDirFileResultSuccess => {
            return {
                file: filename,
                copied: true,
            };
        }).catch((err): DynamicWallpaper.CopyDirFileResultFail => {
            return {
                file: filename,
                copied: false,
                reason: err,
            };
        });
    }

    public static implementScreenDirWith(dir: string = DynamicWallpaper.DIR_SAVE): Promise<DynamicWallpaper.CopyDirFileResult[]> {
        return FileSystem.getAllFilesFrom(dir).then((fileItemList) => {
            return Promise.all(fileItemList.map((item) => {
                return DynamicWallpaper.addToScreenProtectedDir(item, FilePath.nodeModule.relative(dir, item));
            }));
        });
    }
}

DynamicWallpaper.implementScreenDirWith().then((resultList) => {
    resultList.forEach((resultItem) => {
        console.log(`${resultItem.file} copy result: ${resultItem.copied}`);
    });
}).catch((err) => {
    console.error(err);
});
